package xiangya.bysj.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import xiangya.bysj.annotation.WebValidate;
import xiangya.bysj.entity.Admin;

public class WebValidateInterceptor extends HandlerInterceptorAdapter {

	private final String admin_key = "admin";
	private final String login_url = "login";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean result = false;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			WebValidate annotation = handlerMethod.getMethod().getAnnotation(WebValidate.class);
			if (annotation != null && annotation.isValidate()) {
				Admin admin = (Admin) request.getSession().getAttribute(admin_key);
				if(admin != null){
					result = true;
				}else{
					response.sendRedirect(login_url);
					result = false;
				}
			} else {
				result = true;
			}
		} else {
			return false;
		}
		return result;
	}

}
